package com.fast.develop.configuration;

import com.fast.develop.configuration.properties.FastDevelopPropesties;
import com.fast.develop.configuration.tools.browse.BrowseCommand;
import com.fast.develop.configuration.tools.print.PrintConsole;
import com.fast.develop.configuration.tools.print.PrintMessage;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 莫寅
 * @createTime 2022-06-26 03:49
 * @desc：
 */
public class FastDevelopCommandLineRunner implements CommandLineRunner {

    private List<CommandLineRunner> commandLineRunners = new ArrayList<>();

    private ApplicationContext applicationContext;
    private FastDevelopPropesties fastDevelopPropesties;

    public FastDevelopCommandLineRunner(ApplicationContext applicationContext, FastDevelopPropesties fastDevelopPropesties) {
        this.applicationContext = applicationContext;
        this.fastDevelopPropesties = fastDevelopPropesties;
        if(fastDevelopPropesties.isEnablePrint()){
            PrintConsole printConsole = new PrintConsole(applicationContext, fastDevelopPropesties);
            printConsole.addPrintMessage(
                    new PrintMessage() {
                        @Override
                        public String getMessage() {
                            return "在chrome|ie11|edge| 高版本浏览器中访问 At http://127.0.0.1:{port}";
                        }
                    }
            );
            addCommandLineRunner(printConsole);
        }
        if(fastDevelopPropesties.isOpenBrowser()){
            addCommandLineRunner(new BrowseCommand(fastDevelopPropesties));
        }
    }

    @Override
    public void run(String... args) {
        commandLineRunners.stream().forEach(commandLineRunner -> {
            try {
                commandLineRunner.run(args);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public void addCommandLineRunner(CommandLineRunner commandLineRunner){
        commandLineRunners.add(commandLineRunner);
    }
}
